package com.it.security;

import com.alibaba.fastjson.JSON;
import com.it.common.ErrorCode;
import com.it.common.FrameResp;
import com.it.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/7/20 10:18 上午
 */

@Component
public class AuthenticationEntryPointImpl  implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        FrameResp result = null;

        if (e instanceof InsufficientAuthenticationException) {
            result = FrameResp.FAILURE(ErrorCode.NOT_PERMIT, "权限不足");
        } else if (e instanceof BadCredentialsException) {
            result = FrameResp.FAILURE(ErrorCode.LOGIN_ERROR, "账号密码错误");
        } else {
            result = FrameResp.FAILURE(ErrorCode.LOGIN_ERROR, "权限不足");
        }

        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
